/*
 * @Copyright: 2017 www.yyfax.com Inc. All rights reserved.
 */
package com.yyfax.pay.common.model.to;

import java.io.Serializable;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.yyfax.framework.exception.YYException;
import com.yyfax.framework.yyfax.YYFaxSignUtil;
import com.yyfax.framework.yyfax.enums.RspCodeEnum;

/**
 * 支付模块请求包封装
 * 
 * @author jiangmy
 * @date 2017-04-11 13:57:54
 * @since v1.0.0
 */
@SuppressWarnings("serial")
public class YYPayApiReq<P extends YYPayParams> implements Serializable, Signable {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 签名参数,用于YYPayApiReq本身和Params里面的参数合起来按前面算法签名后的结果.
	 */
	private String sign;

	/**
	 * 参数列表
	 */
	@Valid
	private P params;

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public P getParams() {
		return params;
	}

	public void setParams(P params) {
		this.params = params;
	}

	public boolean validate() throws Exception {
		return this.params.validate();
	}

	public boolean checkSign(String key) throws YYException {
		if(!StringUtils.equals(this.sign, sign(key))){
			throw new YYException(RspCodeEnum.COMMON_ERROR_NO_SIGN_AUTHENTICATION);
		}
		
		return true;
	}

	@JsonIgnore
	public String sign(String key) {
		return YYFaxSignUtil.md5Sign(params, key, params.signFields());
	}

	@Override
	public String sign() {
		return null;
	}

}
